import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//导入组件
import login from '../views/user/login.vue'
import home from '../views/home/home.vue'
import qa from '../views/QA/qa.vue'
import movie from '../views/movie/movie.vue'
import user from '../views/user/user.vue'
import layout from '../views/layout.vue'
import notfound from '../views/notfound/notfound.vue'
import edit from '../views/user/edit.vue'
import myarticle from '../views/home/article.vue'
import search from '../views/home/search.vue'
import searchResult from '../views/home/serarchResult.vue'
import student from '../views/home/student.vue'
//路由规则
const routes = [
  {
    path: '/login',
    name: 'login',
    component: login
    // meta:{
    //   key:value,
    //   key2:value2
    // }
  },
  {
    path: '/',
    name: 'layout',
    component: layout,
    children: [
      {
        path: '/home',
        name: 'home',
        component: home
      },
      {
        path: '/movie',
        name: 'movie',
        component: movie
      },
      {
        path: '/qa',
        name: 'qa',
        component: qa
      },
      {
        path: '/user',
        name: 'user',
        component: user,
        //只有跳转user页面才需要做判断，所以要添加路由元信息
        meta: { isLogin: true }
      },
      {
        path: '/',
        //重定向
        redirect: '/login'
      }
    ]
  },
  {
    path: '/notfound',
    name: 'notfound',
    component: notfound
  },
  {
    path: '/searchResult',
    name: 'searchResult',
    component: searchResult
  },
  {
    path: '/student',
    name: 'student',
    component: student
  },
  {
    path: '/myarticle',
    name: 'myarticle',
    component: myarticle
  },
  {
    path: '/search',
    name: 'search',
    component: search
  },
  {
    //任何路劲*
    path: '*',
    redirect: '/notfound'
  },
  {
    path: '/edit',
    name: 'edit',
    component: edit
  }
]
// /*在创建router实例对象之前，手动覆盖原型链的push来吞掉报错catahc */
// const originPush = VueRouter.prototype.push
// //覆盖原型链的push
// VueRouter.prototype.push =function(location,resolve,reject){
//   //判断用户有没有传后面两个可选参数
//   if(resolve || reject){
//     return originPush.call(this,location,resolve,reject)
//   }else{//用户只传了第一个参数
//     /* 默认底层：catah()方法代码 throw err ：抛出异常
//     吞掉报错原理：把默认底层的throw err 给去掉，就不会抛出异常

//     */
//     return originPush.call(this.location).catch(err=>{

//     })
//   }
// }
const router = new VueRouter({
  routes
})
import { getTokey } from '../utils/token'
router.beforeEach((to, from, next) => {
  //判断用户是否需要登录检查
  //getTokey()是否存在
  if (to.meta.isLogin && !getTokey()) {
    next({ path: '/login' })
  } else {
    next()
  }
})
export default router
